// pages/goods_list/index.js
import { request } from '../../request/index.js';
const regeneratorRuntime = require('../../lib/runtime/runtime.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        value: '综合',
        id: 1,
        isActive: true,
      },
      {
        value: '价格',
        id: 2,
        isActive: false,
      },
      {
        value: '销量',
        id: 3,
        isActive: false,
      },
    ],
    // 接口参数
    queryParams: {
      query: '',
      cid: '',
      pagenum: 1,
      pagesize: 10,
    },
    goodsList: [],// 接口list
    totalPages: 5, // 总页数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    let { queryParams } = this.data;
    console.log(queryParams);
    queryParams.cid = options.cid;
    this.getGoodsList(queryParams);
  },
  /* Tabs组件通信 */
  handletabsItemChange(e) {
    console.log(e);
    // 获取索引
    let { index } = e.detail;
    console.log('index', index);
    // 修改tabs中的isActive
    let { tabs } = this.data;
    // tabs.forEach((item, index2) => {
    //   if (index2 === index) {
    //     item.isActive = true;
    //   } else {
    //     item.isActive = false;
    //   }
    // });
    // 简化上面的代码
    tabs.forEach((item, index2) => index2 === index ? item.isActive = true : item.isActive = false);
    console.log(tabs);
    this.setData({
      tabs,
    })
  },
  // 获取goodsList
  async getGoodsList(params) {
    let { goods, total } = await request({ url: '/goods/search', data: params });
    console.log(goods);
    let totalPages = Math.ceil(total / this.data.queryParams.pagesize);
    console.log(totalPages);
    this.setData({
      // 数据拼接,保留上一页的数据
      goodsList: [...this.data.goodsList, ...goods],
      // totalPages,
    });
    // 关闭下拉刷新动作
    wx.stopPullDownRefresh();
  },
  // 页面滚动到底生命周期函数
  onReachBottom() {
    let { queryParams, totalPages } = this.data;
    console.log('页面滚动到底');
    // 判断页面是否到底
    if (queryParams.pagenum >= totalPages) {
      console.log('已经到底部了');
      wx.showToast({
        title: '没有下一页数据了',
        icon: 'error',
        duration: 2000,
      })
    } else {
      // 继续请求
      queryParams.pagenum++;
      this.getGoodsList(queryParams);
    }
  },
  // 下拉刷新生命周期函数
  onPullDownRefresh() {
    // 初始化数据
    this.setData({
      goodsList: [],
    });
    this.data.queryParams.pagenum = 1;
    this.getGoodsList(this.data.queryParams);
  }
})